const articleModel = require('../model/ArticleModel')
const {SUCCESS_RESPONSE, FAIL_RESPONSE} = require('../config/index.js')

// 文章分页接口
exports.getArticleList = async (req, res) => {
    // 所有的查询字符串req.query接收的值都是字符串string类型
    let {page, pageSize, title, status, category_id} = req.query;

// 特殊处理 tag_ids 数组参数
    let tag_ids = [];
    for (let i = 0; i < 3; i++) {
        if (req.query[`tag_ids[${i}]`]) {
            tag_ids.push(req.query[`tag_ids[${i}]`]);
        }
    }
// 如果没有找到数组格式，尝试获取逗号分隔的字符串格式
    if (tag_ids.length === 0 && req.query.tag_ids) {
        tag_ids = req.query.tag_ids.split(',');
    }

    console.log('请求参数:', {page, pageSize, title, status, category_id, tag_ids});

    let article = await articleModel.getArticlePage({
        page, pageSize, title, status, category_id, tag_ids
    });

    // console.log('查询结果:', article.list)
    res.json(SUCCESS_RESPONSE({article: article.list, count: article.total}, '获取文章列表成功'))
}

exports.addArticle = async (req, res) => {

    // 1.获取当前用户id
    req.body.admin_id = req.admin_id

    // 2. 编写sql语句添加数据,
    let result = await articleModel.insertArticle(req.body)

    if (result.affectedRows) {
        // 3. 成功
        res.json(SUCCESS_RESPONSE({}, '添加文章成功'))
    } else {
        // 3. 失败
        res.json(FAIL_RESPONSE({}, '添加文章失败', '00007'))
    }
}

exports.setArticleStatus = async (req, res) => {
    let {article_id, newStatus} = req.query
    console.log('----' + article_id, newStatus)
    let result = await articleModel.updateArticleStatus(article_id, newStatus)
    if (result.affectedRows) {
        // 3. 成功
        res.json(SUCCESS_RESPONSE({}, '修改发布状态成功'))
    } else {
        // 3. 失败
        res.json(FAIL_RESPONSE({}, '修改发布状态失败', '00007'))
    }
}

exports.deleteArticle = async (req, res) => {
    let {article_id} = req.query
    let result = await articleModel.deleteArticleById(article_id)
    if (result.affectedRows) {
        // 3. 成功
        res.json(SUCCESS_RESPONSE({}, '删除文章成功'))
    } else {
        // 3. 失败
        res.json(FAIL_RESPONSE({}, '删除状态失败', '00007'))
    }
}

exports.setArticle = async (req, res) => {
    // 1.获取当前用户id
    req.body.admin_id = req.admin_id

    let result = await articleModel.updateArticle(req.body)
    if (result.affectedRows) {
        // 3. 成功
        res.json(SUCCESS_RESPONSE({}, '修改文章成功'))
    } else {
        // 3. 失败
        res.json(FAIL_RESPONSE({}, '修改文章失败', '00007'))
    }
}


